/**
 * Created by felix on 2016/10/27.
 */
import React from 'react';
import moment from 'moment';
import {Form, Row, Col, Input, DatePicker, Select, Checkbox, Radio} from 'antd';
import ToolBar from './toolBar';
import RemarkInput from './remarkInput';
import IT from './inputTip';
const FormItem = Form.Item,
    RadioButton = Radio.Button,
    RadioGroup = Radio.Group,
    CheckboxGroup = Checkbox.Group,
    Option = Select.Option;

export default class OW extends React.Component {
    /**
     * 初始化属性
     * @tid string 控件类型
     * @i int 循环控件时的索引
     * @initial object 初始值，可能是个空对象{}
     * @formConfig array 表单组的配置
     *  [
     *      {
     *          @type 表单类型
     *          @name 表单项的名称
     *          @rules 表单验证规则
     *          @label 表单标签
     *          @placeholder 默认提示语
     *          @size 空间组中单个控件宽度，全宽等分6份，xs=1x sm=2x md=4x lg=6x
     *          @tips input控件的tips相当于autoComplete的提示 或者 select、radio、checkbox等控件的选项
     *      },{...}
     *  ]
     * @gdf function of antd {getFieldDecorator} = this.props.form
     */
    constructor(props) {
        super(props);
        const hasRemark = this.props.initial && this.props.initial.remark;
        this.state = {
            tid: this.props.tid,
            i: this.props.i,
            initial: this.props.initial,
            formConfig: this.props.formConfig,
            _form_: this.props._form_,
            hasRemark: !!hasRemark || hasRemark === '',
            tipShow: false
        };
    }

    componentWillMount() {
        this.setOpts(this.props.formConfig.opts);
    }

    componentWillReceiveProps(np) {
        const hasRemark = np.initial && np.initial.remark;
        this.setState({
            tid: np.tid,
            i: np.i,
            initial: np.initial,
            formConfig: np.formConfig,
            hasRemark: !!hasRemark || hasRemark === '',
        }, () => this.setOpts(np.formConfig.opts));
    }

    setProps(type, cfg) {
        const tid = this.state.tid,
            i = this.state.i,
            _form_ = this.state._form_,
            _this = this,
            itemId = `${tid}_${[cfg.n]}_${i}`;
        let initial = this.state.initial[cfg.n];
        const add = {};
        add.onChange = (v) => _this.updateValue(
            {
                value: v.target.value,
                tid,
                i,
                name: cfg.n
            }
        );
        if (type === 'checkbox') {
            add.onChange = (v) => _this.updateValue(
                {
                    value: v,
                    tid,
                    i,
                    name: cfg.n
                }
            );
        }
        if (type === 'datepicker') {
            if (initial) {
                initial = moment(initial, "YYYY-MM-DD");
            }
            if (cfg.disabledDate) {
                add.disabledDate = cfg.disabledDate;
            }
            add.onChange = (v1, v2) => _this.updateValue(
                {
                    value: v2,
                    tid,
                    i,
                    name: cfg.n
                }
            );
            add.fomat = "YYYY-MM-DD";
        }
        return _form_.getFieldDecorator(itemId, {
            initialValue: initial,
            rules: cfg.r,
            disabled: cfg.disabled,
            ...add
        });
    }

    setOpts(opts) {
        this.setState({
            opts
        });
    }

    updateValue(obj) {
        if (typeof this.props.updateValue === 'function') {
            this.props.updateValue(obj);
        }
    }

    /*toolEvent(type) {
     if (typeof this.props[type] === 'function') {
     this.props[type](this.state.tid, this.state.i);
     }
     }*/
    toolEvent(type) {
        if (typeof this.props.toolEvent === 'function') {
            this.props.toolEvent(type, this.state.tid, this.state.i);
        }
    }

    inputFocus(id) {
        this.setState({
            onFocus: id
        });
    }

    inputBlur() {
        const _this = this;
        setTimeout(() => {
            _this.setState({
                onFocus: null
            });
        }, 300);
    }

    tipClick(id, value) {
        const {setFieldsValue} = this.state._form_;
        this.setState({
            onFocus: null
        }, () => {
            setFieldsValue({[id]: value});
        });
    }

    definedForm(type, cfg, i) {
        let _dom_;
        const props = this.setProps(type, cfg),
            tips = cfg.tips,
            respond = OW.size[cfg.size],
            id = `${this.state.tid}_${[cfg.n]}_${this.state.i}`,
            showTip = (this.state.onFocus === id);
        switch (type) {
        case 'input':
            _dom_ = props(
                <Input
                    placeholder={cfg.plh}
                    onFocus={this.inputFocus.bind(this, id)}
                    onBlur={this.inputBlur.bind(this)}
                />
            );
            break;
        case 'select':
            _dom_ = props(<Select
                placeholder={cfg.plh}
                showSearch
                optionFilterProp="children"
                notFoundContent="未找到..."
            >
                {tips.map((o, i) => <Option key={`${id}_${i}`} value={o.value}>{o.label}</Option>)}
            </Select>);
            break;
        case 'datepicker':
            _dom_ = (
                props(
                    <DatePicker />
                )
            );
            break;
        case 'checkbox':
            _dom_ = props(
                <CheckboxGroup
                    options={tips}
                />
            );
            break;
        case 'radio':
            _dom_ = props(
                <RadioGroup>
                    {tips.map((o, i) => <RadioButton key={`${id}_${i}`} value={o.value}>{o.label}</RadioButton>)}
                </RadioGroup>
            );
            break;
        default:
            _dom_ = (
                <Input
                    placeholder={cfg.plh}
                />
            );
            break;
        }
        const _it_ = ((t) => {
            if (t === 'input') {
                return (
                    <IT
                        show={showTip}
                        forId={id}
                        data={tips}
                        tipClick={this.tipClick.bind(this)}
                    />
                );
            }
            return '';
        })(type);
        return (
            <Col
                key={i}
                {...respond}
                style={{
                    height: '82px'
                }}
            >
                <div
                    style={{
                        padding: '0 5px'
                    }}
                    id={`id_${i}`}
                >
                    <FormItem
                        label={cfg.l}
                        style={{
                            position: 'relative'
                        }}
                    >
                        {_dom_}
                        {_it_}
                    </FormItem>
                </div>
            </Col>
        );
    }

    _formsRender() {
        const _this = this,
            formConfig = this.state.formConfig;
        return formConfig.map((d, i) => {
            const t = d.type,                                  //表单项的类型 string ''
                cfg = {
                    l: d.label,                                //表单项的标签 string ''
                    n: d.name,                                 //表单项的名称，用于取值 string ''
                    r: d.rules || [],                          //表单项的验证规则 array []
                    plh: d.placeholder,                        //表单项的输入提示 string ''
                    size: d.size || 'sm',                      //表单项的宽度 string 'sm'
                    tips: d.tips,                              //选项，select、radio、checkbox有效 array []
                    getTips: '',
                    disabledDate: d.disabledDate,              //不可用的数据，date类型有效，表示不可用的时间选择范围 function null
                    disabled: d.disabled                       //表单不可用 boolean false
                };
            return _this.definedForm(t, cfg, i);
        });
    }

    renderRemark() {
        return (
            <RemarkInput
                value={this.state.initial.remark}
                tid={this.state.tid}
                form={this.state._form_}
                i={this.state.i}
                updateValue={this.updateValue.bind(this)}
            />
        );
    }

    render() {
        const id = `${this.state.tid}_${this.state.i}`,
            hasRemark = this.state.hasRemark,
            toolBarProps = {
                id,
                hasRemark,
                toolEvent: this.toolEvent.bind(this)
            };
        return (
            <div
                className="owWrap"
            >
                <Row
                    style={{
                        paddingTop: '10px'
                    }}
                >
                    {this._formsRender()}
                    {hasRemark ? this.renderRemark() : null}
                </Row>
                <ToolBar
                    {...toolBarProps}
                />
            </div>
        );
    }
}
OW.size = {
    xs: {
        xs: {
            span: 24
        },
        sm: {
            span: 24
        },
        md: {
            span: 12
        },
        lg: {
            span: 4
        }
    },
    sm: {
        xs: {
            span: 24
        },
        sm: {
            span: 24
        },
        md: {
            span: 12
        },
        lg: {
            span: 8
        }
    },
    md: {
        xs: {
            span: 24
        },
        sm: {
            span: 24
        },
        md: {
            span: 24
        },
        lg: {
            span: 16
        }
    },
    lg: {
        xs: {
            span: 24
        },
        sm: {
            span: 24
        },
        md: {
            span: 24
        },
        lg: {
            span: 24
        }
    }
};
